<template>
  <div class="daily-practices-container">
    <!-- 顶部标题区域 -->
    <div class="header-section">
      <div class="title-container">
        <h1><i class="el-icon-notebook-2"></i> 每日练习</h1>
        <p class="subtitle">每天进步一点点，知识积累一大步</p>
      </div>
      <!-- 只在有练习时显示统计卡片 -->
      <div class="stats-card" v-if="practices.length > 0">
        <div class="stat-item">
          <div class="stat-value">{{ practices.length }}</div>
          <div class="stat-label">今日题数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ completedCount }}/{{ practices.length }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ formatTime(totalPracticeTime) }}</div>
          <div class="stat-label">总用时</div>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-alert :title="error" type="error" show-icon />
      </div>
      
      <div v-else-if="practices.length === 0" class="no-practices-container">
        <!-- 使用Element图标替代图片 -->
        <el-empty description="今日没有待完成的练习题目">
          <i class="el-icon-document-remove" style="font-size: 60px; color: #909399;"></i>
          <template #footer>
            <el-button type="primary" @click="fetchDailyPractices">刷新练习</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else class="content-with-sheet">
        <div class="practices-and-results">
          <!-- 练习题目部分 -->
          <div v-if="!showResults" class="practices-list">
            <div v-for="(practice, index) in practices" :key="index" class="practice-card" :id="`question-${index}`">
              <div class="card-header">
                <div class="tags-container">
                  <el-tag type="info" size="small">{{ practice.subject }}</el-tag>
                  <el-tag type="info" size="small">{{ practice.examType }}</el-tag>
                  <el-tag :type="getTagType(practice.questionType)" size="small">
                    {{ getQuestionTypeName(practice.questionType) }}
                  </el-tag>
                </div>
                <div class="question-index">#{{ index + 1 }}</div>
              </div>
              
              <div class="question-content" v-html="formatQuestionContent(practice.questionContent)"></div>
              
              <!-- 选择题选项 -->
              <div v-if="practice.questionType === 'single_choice' && practice.choices" class="choices-container">
                <div v-for="(choice, choiceIndex) in parseChoices(practice.choices)" 
                     :key="choiceIndex" 
                     class="choice-item"
                     :class="{ 'selected': userAnswers[index].answer === String.fromCharCode(65 + choiceIndex) }"
                     @click="selectChoice(index, String.fromCharCode(65 + choiceIndex))">
                  <div class="choice-letter">{{ String.fromCharCode(65 + choiceIndex) }}.</div>
                  <div class="choice-text" v-html="formatQuestionContent(choice)"></div>
                </div>
              </div>
              
              <!-- 填空题 -->
              <div v-if="practice.questionType === 'fill_in_the_blank'" class="answer-input">
                <el-input
                  v-model="userAnswers[index].answer"
                  placeholder="请输入您的答案"
                  clearable
                ></el-input>
              </div>
              
              <!-- 主观题 -->
              <div v-if="practice.questionType === 'subjective'" class="answer-textarea">
                <el-input
                  v-model="userAnswers[index].answer"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入您的解答"
                ></el-input>
              </div>
            </div>
          </div>
          
          <!-- 批改结果部分 -->
          <div v-if="showResults" class="results-container">
            <div class="result-summary">
              <div class="summary-card">
                <div class="summary-item correct">
                  <div class="summary-value">{{ correctCount }}</div>
                  <div class="summary-label">正确</div>
                </div>
                <div class="summary-item wrong">
                  <div class="summary-value">{{ wrongCount }}</div>
                  <div class="summary-label">错误</div>
                </div>
                <div class="summary-item unchecked">
                  <div class="summary-value">{{ uncheckedCount }}</div>
                  <div class="summary-label">未批改</div>
                </div>
                <div class="summary-item">
                  <div class="summary-value">{{ formatTime(totalPracticeTime) }}</div>
                  <div class="summary-label">总用时</div>
                </div>
              </div>
            </div>
            
            <div v-for="(result, index) in results" :key="index" class="result-card" :id="`question-${index}`">
              <div class="card-header">
                <div class="tags-container">
                  <el-tag type="info" size="small">{{ result.subject }}</el-tag>
                  <el-tag type="info" size="small">{{ result.examType }}</el-tag>
                  <el-tag :type="getTagType(result.questionType)" size="small">
                    {{ getQuestionTypeName(result.questionType) }}
                  </el-tag>
                  <el-tag v-if="result.isCorrect !== null" 
                          :type="result.isCorrect ? 'success' : 'danger'" 
                          size="small">
                    {{ result.isCorrect ? '正确' : '错误' }}
                  </el-tag>
                  <el-tag v-else type="warning" size="small">未批改</el-tag>
                </div>
                <div class="question-index">#{{ index + 1 }}</div>
              </div>
              
              <div class="question-content" v-html="formatQuestionContent(result.questionContent)"></div>
              
              <!-- 显示选择题选项 -->
              <div v-if="result.questionType === 'single_choice' && result.choices" class="choices-container">
                <div v-for="(choice, choiceIndex) in parseChoices(result.choices)" 
                     :key="choiceIndex" 
                     class="choice-item"
                     :class="{
                       'user-selected': result.userAnswer === String.fromCharCode(65 + choiceIndex),
                       'correct-option': result.correctAnswer === String.fromCharCode(65 + choiceIndex)
                     }">
                  <div class="choice-letter">{{ String.fromCharCode(65 + choiceIndex) }}.</div>
                  <div class="choice-text">
                    <span v-html="formatQuestionContent(choice)"></span>
                    <span v-if="result.userAnswer === String.fromCharCode(65 + choiceIndex)" class="selection-marker">(您的选择)</span>
                    <span v-if="result.correctAnswer === String.fromCharCode(65 + choiceIndex)" class="correct-marker">(正确答案)</span>
                  </div>
                </div>
              </div>
              
              <div class="answer-container">
                <div v-if="result.questionType !== 'single_choice'" class="answer-item">
                  <span class="answer-label">您的答案：</span>
                  <span class="user-answer" v-html="formatQuestionContent(result.userAnswer || '未作答')"></span>
                </div>
                <div v-if="result.questionType !== 'single_choice'" class="answer-item">
                  <span class="answer-label">正确答案：</span>
                  <span class="correct-answer" v-html="formatQuestionContent(result.correctAnswer || '')"></span>
                </div>
                <div v-if="result.analysis" class="analysis-container">
                  <div class="answer-label">答案解析：</div>
                  <div class="analysis-content" v-html="formatQuestionContent(result.analysis)"></div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button 
              v-if="!showResults" 
              type="primary" 
              class="submit-btn"
              @click="showSubmitConfirm"
              :disabled="completedCount < practices.length">
              <i class="el-icon-s-promotion"></i> 提交答案
            </el-button>
            <el-button 
              v-else 
              type="primary" 
              class="submit-btn"
              @click="fetchDailyPractices">
              <i class="el-icon-refresh"></i> 新的练习
            </el-button>
          </div>
        </div>
        
        <!-- 答题卡区域 -->
        <div class="answer-sheet">
          <div class="sheet-title">答题卡</div>
          <div v-for="(subjectGroup, subject) in groupedPractices" :key="subject" class="subject-group">
            <div class="subject-name">{{ subject }}</div>
            <div v-for="(questions, type) in subjectGroup" :key="type" class="type-group">
              <div class="type-name">{{ getQuestionTypeName(type) }}</div>
              <div class="questions-container">
                <div 
                  v-for="q in questions" 
                  :key="q.index" 
                  class="question-box"
                  :class="{ 
                    answered: userAnswers[q.index].answer,
                    current: currentQuestionIndex === q.index
                  }"
                  @click="scrollToQuestion(q.index)">
                  {{ q.index + 1 }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认提交弹窗 -->
    <el-dialog
      v-model="showConfirmModal"
      title="确认提交"
      width="400px"
      center>
      <div class="confirm-dialog">
        <div class="dialog-icon">
          <i class="el-icon-warning" style="color: #e6a23c; font-size: 48px;"></i>
        </div>
        <p class="dialog-text">您确定要提交所有答案吗？提交后将无法修改。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConfirmModal = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmSubmit">确认提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import axios from 'axios';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';

// 导入KaTeX
import 'katex/dist/katex.min.css';
import katex from 'katex';

const userStore = useUserStore();
const practices = ref([]);
const loading = ref(true);
const error = ref(null);
const userAnswers = ref([]);
const results = ref([]);
const showResults = ref(false);
const showConfirmModal = ref(false);
const timerRef = ref(null);
const totalPracticeTime = ref(0); // 整个练习的总时间（秒）
const startTime = ref(null); // 练习开始时间戳
const currentQuestionIndex = ref(0); // 当前正在做的题目索引

// ====================== LaTeX渲染相关 ======================
/* 格式化题目内容 - 使用KaTeX处理数学公式 */
const formatQuestionContent = (content) => {
  if (!content) return '';
  
  try {
    let processedContent = content
      .replace(/\\n/g, '\n')  // 处理换行符
      .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
      .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
        // 处理块级数学公式 $$...$$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: true,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX block formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$$${formula}$$</span>`;
        }
      })
      .replace(/\$([^$\n]+)\$/g, (match, formula) => {
        // 处理行内数学公式 $...$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: false,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$${formula}$</span>`;
        }
      })
      .replace(/###DOLLAR###/g, '$')  // 恢复转义的美元符号
      .replace(/\n/g, '<br>');  // 简单的换行处理
    
    return processedContent;
  } catch (error) {
    console.error('formatQuestionContent error:', error);
    return content.replace(/\\n/g, '<br>');
  }
};

// 监听滚动事件来更新当前题目索引
onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
  if (timerRef.value) {
    clearInterval(timerRef.value);
  }
});

// 计算属性
const completedCount = computed(() => {
  return userAnswers.value.filter(item => item.answer).length;
});

const correctCount = computed(() => {
  return results.value.filter(item => item.isCorrect === true).length;
});

const wrongCount = computed(() => {
  return results.value.filter(item => item.isCorrect === false).length;
});

const uncheckedCount = computed(() => {
  return results.value.filter(item => item.isCorrect === null).length;
});

// 分组计算属性 - 按科目和题型分组
const groupedPractices = computed(() => {
  const groups = {};
  
  practices.value.forEach((practice, index) => {
    // 初始化科目
    if (!groups[practice.subject]) {
      groups[practice.subject] = {
        single_choice: [],
        fill_in_the_blank: [],
        subjective: []
      };
    }
    
    // 添加题目到对应分组
    groups[practice.subject][practice.questionType].push({
      ...practice,
      index: index
    });
  });
  
  return groups;
});

const fetchDailyPractices = async () => {
  try {
    loading.value = true;
    error.value = null;
    showResults.value = false;
    totalPracticeTime.value = 0;
    
    const userId = userStore.userId;
    if (!userId) {
      throw new Error('用户未登录');
    }

    const response = await axios.get('/api/daily-practices', {
      params: { userId }
    });
    
    practices.value = response.data;
    userAnswers.value = practices.value.map(practice => ({
      questionId: practice.questionId,
      answer: '',
      timeSpent: 0,
      choices: practice.choices
    }));
    
    // 清除之前的计时器
    if (timerRef.value) {
      clearInterval(timerRef.value);
    }
    
    // 记录练习开始时间
    startTime.value = new Date();
    
    // 设置新的计时器 - 每秒更新一次总时间
    timerRef.value = setInterval(() => {
      if (startTime.value && !showResults.value) {
        const now = new Date();
        totalPracticeTime.value = Math.floor((now - startTime.value) / 1000);
      }
    }, 1000);
    
  } catch (err) {
    error.value = '获取每日练习失败: ' + (err.response?.data?.message || err.message);
    console.error('获取每日练习失败:', err);
  } finally {
    loading.value = false;
  }
};

const getTagType = (questionType) => {
  const typeMap = {
    'single_choice': 'success',
    'fill_in_the_blank': 'warning',
    'subjective': 'danger'
  };
  return typeMap[questionType] || 'info';
};

const getQuestionTypeName = (type) => {
  const typeMap = {
    'single_choice': '单选题',
    'fill_in_the_blank': '填空题',
    'subjective': '主观题'
  };
  return typeMap[type] || type;
};

const parseChoices = (choicesString) => {
  if (!choicesString) return [];
  
  try {
    // 如果是JSON字符串，解析为对象
    if (choicesString.startsWith("{")) {
      const options = JSON.parse(choicesString);
      return Object.values(options); // 返回选项值数组
    }
    // 如果是逗号分隔的字符串
    return choicesString.split(',').filter(choice => choice.trim() !== '');
  } catch (e) {
    console.error('解析选择题选项失败:', e);
    return [];
  }
};

const selectChoice = (index, choice) => {
  userAnswers.value[index].answer = choice;
};

const showSubmitConfirm = () => {
  if (completedCount.value < practices.value.length) {
    ElMessage.warning('请完成所有题目后再提交');
    return;
  }
  showConfirmModal.value = true;
};

const handleConfirmSubmit = async () => {
  showConfirmModal.value = false;
  await submitAnswers();
};

const submitAnswers = async () => {
  try {
    // 确保提交总用时
    const submissionData = {
      userId: userStore.userId,
      answers: userAnswers.value.map(item => ({
        questionId: item.questionId,
        answer: item.answer,
        timeSpent: item.timeSpent,
        choices: item.choices
      })),
      totalTime: totalPracticeTime.value // 确保提交总用时
    };

    const response = await axios.post('/api/daily-practices/submit', submissionData);
    
    if (response.data) {
      results.value = response.data.map((result, index) => ({
        ...result,
        choices: userAnswers.value[index].choices
      }));
      showResults.value = true;
      
      // 停止计时器
      if (timerRef.value) {
        clearInterval(timerRef.value);
        timerRef.value = null;
      }
    } else {
      ElMessage.error('提交失败，请稍后重试');
    }
  } catch (err) {
    console.error('提交答案失败:', err);
    ElMessage.error('提交失败: ' + (err.response?.data?.message || err.message));
  }
};

const formatTime = (seconds) => {
  if (!seconds) return '00:00';
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};

// 滚动到指定题目
const scrollToQuestion = (index) => {
  const element = document.getElementById(`question-${index}`);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    currentQuestionIndex.value = index;
  }
};

// 处理滚动事件更新当前题目
const handleScroll = () => {
  if (showResults.value) return;
  
  const questionElements = document.querySelectorAll('.practice-card');
  let closestIndex = 0;
  let closestDistance = Infinity;
  
  questionElements.forEach((element, index) => {
    const rect = element.getBoundingClientRect();
    const distance = Math.abs(rect.top);
    
    if (distance < closestDistance) {
      closestDistance = distance;
      closestIndex = index;
    }
  });
  
  currentQuestionIndex.value = closestIndex;
};

onMounted(() => {
  fetchDailyPractices();
});
</script>

<style scoped>
.daily-practices-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-container h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-container h1 i {
  color: #409EFF;
}

.subtitle {
  font-size: 16px;
  color: #909399;
  margin: 0;
}

.stats-card {
  display: flex;
  gap: 20px;
  background: linear-gradient(135deg, #f0f7ff, #e6f7ff);
  padding: 15px 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.stat-item {
  text-align: center;
  padding: 0 15px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.main-content {
  margin-top: 20px;
}

.content-with-sheet {
  display: flex;
  gap: 20px;
}

.practices-and-results {
  flex: 1;
}

.answer-sheet {
  width: 280px;
  background: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  align-self: flex-start;
  position: sticky;
  top: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

.sheet-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.subject-group {
  margin-bottom: 15px;
}

.subject-name {
  font-weight: bold;
  margin: 10px 0 5px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
  font-size: 16px;
}

.type-name {
  font-size: 14px;
  color: #909399;
  margin: 8px 0;
}

.questions-container {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.question-box {
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.question-box:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.question-box.answered {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

.question-box.current {
  border: 2px solid #e6a23c;
  box-shadow: 0 0 0 2px rgba(230, 162, 60, 0.2);
}

.practice-card,
.result-card {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.practice-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tags-container {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.question-index {
  font-size: 16px;
  font-weight: 600;
  color: #909399;
  background-color: #f5f7fa;
  padding: 4px 10px;
  border-radius: 20px;
}

.question-content {
  font-size: 16px;
  line-height: 1.7;
  color: #303133;
  margin-bottom: 20px;
}

/* KaTeX样式优化 */
.question-content :deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
}

.question-content :deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
}

.question-content :deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.choices-container {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin: 15px 0;
}

.choice-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 15px;
  border-radius: 8px;
  background-color: #f8fafc;
  border: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.2s;
}

.choice-item:hover {
  background-color: #f0f7ff;
  border-color: #c6e2ff;
}

.choice-item.selected {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

.choice-letter {
  font-weight: 600;
  color: #1890ff;
  min-width: 24px;
}

.choice-text {
  flex: 1;
  line-height: 1.6;
}

/* 选项中的KaTeX样式 */
.choice-text :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.choice-text :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
}

.answer-input,
.answer-textarea {
  margin-top: 15px;
}

.result-summary {
  margin-bottom: 30px;
}

.summary-card {
  display: flex;
  justify-content: space-around;
  background: linear-gradient(135deg, #f6ffed, #f0fff3);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.1);
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-item.correct .summary-value {
  color: #52c41a;
}

.summary-item.wrong .summary-value {
  color: #ff4d4f;
}

.summary-item.unchecked .summary-value {
  color: #faad14;
}

.summary-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
}

.answer-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
}

.answer-item {
  display: flex;
  margin-bottom: 15px;
}

.answer-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
}

.user-answer {
  color: #ff4d4f;
  font-weight: 500;
}

.correct-answer {
  color: #52c41a;
  font-weight: 500;
}

/* 答案区域的KaTeX样式 */
.user-answer :deep(.katex),
.correct-answer :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.user-answer :deep(.katex-display),
.correct-answer :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
}

.analysis-container {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e8e8e8;
}

.analysis-content {
  margin-top: 10px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  line-height: 1.7;
  color: #606266;
  border-left: 3px solid #1890ff;
}

/* 解析区域的KaTeX样式 */
.analysis-content :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.analysis-content :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: center;
}

.user-selected {
  background-color: #fff2f0;
  border-color: #ffccc7;
}

.correct-option {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

.selection-marker {
  color: #ff4d4f;
  margin-left: 8px;
  font-size: 0.9em;
}

.correct-marker {
  color: #52c41a;
  margin-left: 8px;
  font-size: 0.9em;
}

.action-buttons {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.submit-btn {
  padding: 12px 35px;
  font-size: 16px;
  border-radius: 30px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.3s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.confirm-dialog {
  text-align: center;
  padding: 20px 0;
}

.dialog-icon {
  margin-bottom: 20px;
}

.dialog-text {
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
}

.loading-container,
.error-container,
.no-practices-container {
  margin-top: 40px;
}

/* KaTeX全局样式优化 */
:deep(.katex) {
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}

@media (max-width: 992px) {
  .content-with-sheet {
    flex-direction: column;
  }
  
  .answer-sheet {
    width: 100%;
    margin-top: 20px;
    position: static;
    max-height: none;
  }
  
  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }
  
  .stats-card {
    width: 100%;
    justify-content: space-around;
  }
  
  .stat-item {
    padding: 0 5px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 15px;
  }
  
  .submit-btn {
    width: 100%;
  }
  
  .summary-card {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .summary-item {
    flex: 0 0 calc(50% - 15px);
  }
}
</style>